package org.sun.sunshine.websocket;

import java.io.IOException;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


@ServerEndpoint(value = "/channel/echo/{usrId}")
public class EchoChannel implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(EchoChannel.class);
    private Session session;
    private static Map<String,Session> sessions=new ConcurrentHashMap<>();
    private static Map<String,String> sessionId2UserId= new ConcurrentHashMap();

    private ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext){
        this.applicationContext = applicationContext;
    }

    // 收到消息
    @OnMessage
    public void onMessage(String message) throws IOException{
        LOGGER.info("[websocket] 收到消息：id={}，message={}", this.session.getId(), message);
        if (message.equalsIgnoreCase("bye")) {
            // 由服务器主动关闭连接。状态码为 NORMAL_CLOSURE（正常关闭）。
            this.session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Bye"));;
            return;
        }
        this.session.getAsyncRemote().sendText("["+ Instant.now().toEpochMilli() +"] connected" + message);
    }

    // 连接打开
    @OnOpen
    public void onOpen(Session session,@PathParam("usrId") String usrId,EndpointConfig endpointConfig) throws IOException {

        //let websocket = new WebSocket("ws://localhost:9090/channel/echo/"+staffId+"?token=xxx");
        String token = session.getRequestParameterMap().get("token").get(0);
        //todo 验证token
        if(token==null){
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY,"token is null"));
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
            }
            return;
        }

        // 保存 session 到对象
        this.session = session;
        //usrId 以登录，注销前一个session
        if(sessions.containsKey(usrId)){
            Session oldSession = sessions.get(usrId);
            oldSession.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE,"您的账号在其他位置登录，您已踢出"));
            sessions.remove(usrId);
            sessionId2UserId.remove(oldSession.getId());
        }
        sessions.put(usrId,session);
        sessionId2UserId.put(session.getId(),usrId);

        //todo sendInitMsg  发送初始信息，连接后的初始信息

        LOGGER.info("[websocket] 新的连接：id={}", this.session.getId());
    }

    //用户下线
    // 连接关闭
    @OnClose
    public void onClose(CloseReason closeReason){
        String userId = sessionId2UserId.get(this.session.getId());
        if(userId!=null){
            sessions.remove(userId);
            sessionId2UserId.remove(this.session.getId());
        }
        LOGGER.info("[websocket] 连接断开：id={}，reason={}", this.session.getId(),closeReason);
    }

    // 连接异常
    @OnError
    public void onError(Throwable throwable) throws IOException {
        LOGGER.info("[websocket] 连接异常：id={}，throwable={}", this.session.getId(), throwable.getMessage());
        // 关闭连接。状态码为 UNEXPECTED_CONDITION（意料之外的异常）
        this.session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, throwable.getMessage()));
    }

    //在广播消息消费时调用此方法进行消息发送，保证消息不会循环放入广播消息队列
    public static void justSendMsg(String userId,String msg){
        Session session = sessions.get(userId);
        if(session!=null){
            session.getAsyncRemote().sendText(msg);
        }
    }

    //发送消息，并判断如果usrId在本地session不存在就广播消息
    public static void sendMsg(String userId,String msg){
        Session session = sessions.get(userId);
        if(session!=null){
            session.getAsyncRemote().sendText(msg);
        }else{
            LOGGER.info("[websocket] 发送消息失败：id={}，msg={}", userId,msg);
            //todo 广播消息，发送到其他节点，进行消息发送，要是所有节点都不存在呢？会不会造成死循环？ 如何保证消息只被广播一次？
            //答：广播消息消费时调用  org.sun.sunshine.websocket.EchoChannel.justSendMsg
        }
    }


}